package NovelBar.service;

import NovelBar.entity.Book;
import NovelBar.entity.User;
import NovelBar.entity.Witer;
import NovelBar.mapper.BookMapper;
import NovelBar.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@Service
public class UserService implements UserDetailsService{
	
	@Autowired
	private UserMapper userMapper;

	@Autowired
	private BookMapper bookMapper;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// TODO Auto-generated method stub
		User user = userMapper.loadUserByUsername(username);
		System.out.println(user.getPassword());
		if (user == null) {
			throw new UsernameNotFoundException("账户不存在！");
		}
		user.setRoles(userMapper.getUserRolesByUid(user.getId()));
		return user;
	}

	public boolean addUser(User user) {
		// TODO Auto-generated method stub
		// 判断当前用户是否存在于数据库中
		if (userMapper.loadUserByUsername(user.getUsername()) == null) {
			// 加密
			BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
			String hashedPassword = passwordEncoder.encode(user.getPassword());
			user.setPassword(hashedPassword);
			userMapper.addUser(user);
			userMapper.setUserRole(userMapper.loadUserByUsername(user.getUsername()).getId(), user.getUsertype());
			if (user.getUsertype() == 1) {
				Witer witer = new Witer();
				witer.setUid(userMapper.loadUserByUsername(user.getUsername()).getId());
				Date date = new Date();
				SimpleDateFormat matter = new SimpleDateFormat("yyyy/MM/dd");
				witer.setCreateDate(matter.format(date).toString());
				witer.setFan(0);
				witer.setSalary("0");
				userMapper.addWiter(witer);
			}
			return true;
		} else {
			return false;
		}
		
	}

	public void updateUsernameByUsername(String oldUsername, String newUsername) {
		// TODO Auto-generated method stub
		userMapper.updateUsernameByUsername(oldUsername, newUsername);
	}

	public Witer loadWiterById(Integer uid) {
		return userMapper.loadWiterById(uid);
	}

	public void banWiter (Integer bookid) {
		Book book = bookMapper.loadBookById(bookid);
		Witer witer = userMapper.loadWiterBywId(book.getWid());
		userMapper.banWiter(witer.getUid());
	}

	public List<User> banUserList() {
		return userMapper.banUserList();
	}

	public void removeBan(Integer id) {
		userMapper.removeBan(id);
	}

	public void charge(Integer id, Integer money) {
		userMapper.charge(id, money);
	}
}
